<?php
namespace web\admin\controller;
class Shop extends Common{
    //动作
	protected $db;
	public function __construct()
	{
		parent::__construct();
		$this->db=new \system\model\Shop();
	}
	public function index(){
		//此处书写代码...
		$data=$this->db->getAll();
		View::with('data',$data);
		View::make();
	}
	//添加
	public function store(){
		if (IS_POST){
//			p($_POST);die;
			if($this->db->store()){
				message('添加成功','index','success');
			}else{
				message($this->db->getError(),'','error');
			}
		}
		//获取所有分类的数据
		$cateData = Data::tree(Db::table('vivo_category')->get(),'cname');
		View::with('cateData',$cateData);
		//获取品牌表的所有数据
		$brankData = Db::table('vivo_brank')->get();
		View::with('brankData',$brankData);
		//获取商品表的所有数据
		View::make();
	}
	//异步获取规格和属性
	public function ajaxGetAttr(){
		$tid = $_POST['tid'];
		$TypeAttrData =Db::table('vivo_typeattr')->where('tid',$tid)->get();
		foreach ($TypeAttrData as $k=>$v){
			//explode按符号把其转化为数组
			$TypeAttrData[$k]['tavalue'] = explode('|',$v['tavalue']);
		}
//		p($TypeAttrData);
		//把数据转化为json类型
		echo json_encode($TypeAttrData);exit;
	}
	public function edit(){
		$sid = q('get.sid',0,'intval');
		if (IS_POST){
			if ($this->db->edit()){
				message('编辑成功',u('index'),'success');
			}else{
				message($this->db->getError(),'back','error');
			}
		}
		//获取旧数据
		//关联商品表和商品详情表，获取当前要编辑的单一数据
		$oldData = $this->db
			->join('vivo_details','vivo_shop.sid','=','vivo_details.sid')
			->where('vivo_shop.sid',$sid)
			->first();
//		p($oldData);
		$oldData['big']=explode(',',$oldData['big']);
//		p($oldData);die;
		View::with('oldData',$oldData);
		//2.处理属性部分
		$attrData = Db::table('vivo_typeattr')->where('taclass',2)->where('tid',$oldData['tid'])->get();
//		把属性项拆分成数组
		foreach ($attrData as $k=>$v){
			$attrData[$k]['tavalue'] = explode('|',$v['tavalue']);
		}
		//p($attrData);
		//在商品属性表获取当前商品添加了那些属性
		$shopAttrData = Db::table('vivo_shopattr')
			->where('sid',$sid)->lists('stvalue');
//		p($shopAttrData);
		View::with('shopAttrData',$shopAttrData);
		View::with('attrData',$attrData);
		//3.处理规格
		$specData = Db::table('vivo_typeattr')
			->join('vivo_shopattr','vivo_typeattr.taid','=','vivo_shopattr.taid')
			->where('sid',$sid)
			->where('taclass',1)
			->get();
//		p($specData);
		foreach ($specData as $k=>$v){
			$specData[$k]['tavalue'] = explode('|',$v['tavalue']);
		}
//				p($specData);

		View::with('specData',$specData);
		//获取所有分类数据
		$cateData = Data::tree(Db::table('vivo_category')->get(),'cname');
		View::with('cateData',$cateData);
		//获取品牌表的所有数据
		$brankData = Db::table('vivo_brank')->get();
		View::with('brankData',$brankData);
		View::make();
	}
	/**
	 * 删除
	 */
	public function del()
	{
		$sid = q('get.sid', 0, 'intval');
		$this->db->where('sid', $sid)->delete();
		Db::table('vivo_details')->where('sid',$sid)->delete();
		Db::table('vivo_shopattr')->where('sid',$sid)->delete();
		message('操作成功', u('index'), 'success');
	}
}
